<template>
  <view class="article-container">
    <!-- 统一的可滚动区域 -->
    <scroll-view :scroll-y="true" class="scroll-content">
      <!-- 帖子内容 -->
      <view v-if="postData" class="post-content">
        <!-- 头部信息 -->
        <view class="header">
          <u-avatar :src="postData.avatar" size="60" @change="navigateToUserProfile(postData.userId)"></u-avatar>
          <view class="user-info">
            <text class="username">{{ postData.name }}</text>
            <view class="details">
              <text>{{ postData.campus }}（{{ postData.grade }}级）</text>
            </view>
          </view>
        </view>
        <!-- 标签 -->
        <view class="tag">
          <text>#{{ postData.tag }}</text>
        </view>
        <!-- 文本内容 -->
        <view class="content">
          <text>{{ postData.title }}</text>
          <text>{{ postData.content }}</text>
        </view>
        <!-- 图片 -->
        <view v-if="postData.images && postData.images.length > 0" class="images">
          <view v-for="(imgUrl, index) in postData.images" :key="index" class="image-item">
            <u-image :src="imgUrl" mode="aspectFill" width="220rpx" height="220rpx"></u-image>
          </view>
        </view>
        <!-- 浏览量、时间和点赞数 -->
        <view class="stats-container">
          <view class="stats-row">
            <view class="views">
              <u-icon name="eye" size="30"></u-icon>
              <text>{{ postData.viewCount }}</text>
            </view>
            <view class="like" @click="handleLike">
              <u-icon :name="isLiked ? 'thumb-up-fill' : 'thumb-up'" size="30"></u-icon>
              <text>{{ postData.likeCount }}</text>
            </view>
          </view>
          <view class="time-row">
            <text>{{ postData.time }}</text>
          </view>
        </view>
      </view>
      <!-- 评论区组件 -->
      <view class="comment-section" v-show="postData">
        <article-txt
            :article-id="postData.id"
            :refresh-key="refreshKey"
        ref="articleTxtRef"
        @reply-comment="handleReplyComment"
        />
      </view>
    </scroll-view>
    <!-- 固定评论输入框 -->
    <view class="fixed-input">
      <comment-input
          @send-comment="refreshComments"
          @clear-reply="clearReplyInfo"
          :reply-to="replyTo"
          :parent-comment-id="parentCommentId"
          :article-id="postData.id"
      />
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { getArticleById } from '@/apis/homeAPI';
import { toggleLike } from '@/apis/articleApi';
import ArticleTxt from '@/components/article-txt/article-txt.vue';
import CommentInput from '@/components/comment-input/comment-input.vue';
import { onLoad } from '@dcloudio/uni-app';

// 初始化postData为包含默认id的对象
const postData = ref({
  id: 1,
  avatar: '',
  name: '',
  campus: '',
  grade: '',
  tag: '',
  title: '',
  content: '',
  viewCount: 0,
  time: '',
  images: [],
  likeCount: 0
});
const articleTxtRef = ref();
const isLiked = ref(false);
const replyTo = ref('');
const parentCommentId = ref(0);

// 用于触发评论刷新的键
const refreshKey = ref(0);

// 刷新评论方法：更新refreshKey触发子组件刷新
const refreshComments = () => {
  refreshKey.value += 1;
  console.log('refreshKey 已递增:', refreshKey.value); // 确认值在变化
  // 手动延迟 100ms 再触发（应对极端情况下的响应式延迟）
  setTimeout(() => {
    refreshKey.value += 1;
    console.log('refreshKey 二次递增:', refreshKey.value);
  }, 100);
};


// 页面加载时获取文章数据
onLoad((options) => {
  const id = options.id || 1;
  fetchArticleData(id);
});

// 获取文章详情
const fetchArticleData = async (id) => {
  try {
    const response = await getArticleById(id);
    console.log('获取文章成功:', response.data);
    if (response.data.code === 200) {
      const article = response.data.data;
      // 修正后：正确解析字符串JSON数组
      let images = [];
      if (article.flie) {
        if (typeof article.flie === 'string') {
          try {
            // 尝试解析字符串为JSON数组（核心修复）
            const parsed = JSON.parse(article.flie);
            images = Array.isArray(parsed) ? parsed : [article.flie];
          } catch (e) {
            // 解析失败时，将字符串作为单个图片路径
            images = [article.flie];
            console.warn('图片路径解析失败', e);
          }
        } else if (Array.isArray(article.flie)) {
          images = article.flie;
        }
      }
      // 更新postData
      postData.value = {
        id: article.id || 1,
        avatar: article.user.avatar || '',
        name: article.user.nickname || '',
        campus: article.user.campus || '金堂校区',
        grade: article.user.grade || '',
        tag: article.tag || '代',
        title: article.title || '',
        content: article.content || '',
        viewCount: article.viewCount || 0,
        time: formatDate(article.createTime) || '',
        images: images,
        likeCount: article.likeCount || 0,
        userId: article.userId || 0,
      };
      // 文章id更新后，主动刷新评论区
      refreshComments();
    }
  } catch (error) {
    console.error('获取文章失败:', error);
  }
};

// 点赞功能
const handleLike = async () => {
  if (!postData.value.id) return;
  try {
    const response = await toggleLike({
      userId: 3,
      targetId: postData.value.id,
      targetType: 1
    });
    if (response.data.code === 200) {
      postData.value.likeCount = response.data.data;
      isLiked.value = !isLiked.value;
    }
  } catch (error) {
    console.error('点赞失败:', error);
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 处理回复评论
const handleReplyComment = (data) => {
  replyTo.value = data.username;
  parentCommentId.value = data.id;
  setTimeout(() => {
    replyTo.value = data.username; // 强制更新
  }, 0);
};

// 清空回复状态
const clearReplyInfo = () => {
  replyTo.value = '';
  parentCommentId.value = 0;
};

// 导航到用户详情页
const navigateToUserProfile = (userId) => {
  if (!userId) return;
  uni.navigateTo({ url: `/pages/profile/profile?userId=${userId}` });
};
</script>

<style scoped lang="scss">
.article-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  .scroll-content {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    height: calc(100vh - 160px);
    .post-content {
      width: 100%;
      .stats-container {
        margin-bottom: 20px;
        .stats-row {
          display: flex;
          align-items: center;
          gap: 20px;
          margin-bottom: 10px;
          .views, .like {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            u-icon {
              vertical-align: middle;
            }
            text {
              font-size: 14px;
              color: #666;
            }
          }
          .like {
            cursor: pointer;
            u-icon {
              transition: color 0.3s;
            }
          }
        }
        .time-row {
          text-align: left;
          text {
            font-size: 12px;
            color: #999;
          }
        }
      }
      .header {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        .user-info {
          margin-left: 10px;
          .username {
            font-size: 16px;
            font-weight: bold;
          }
          .details {
            font-size: 12px;
            color: #999;
          }
        }
      }
      .tag {
        margin-bottom: 20px;
        text {
          background-color: #f5f5f5;
          padding: 5px 10px;
          border-radius: 5px;
        }
      }
      .content {
        margin-bottom: 20px;
        text {
          display: block;
          margin-bottom: 10px;
        }
      }
      ::v-deep .images {
        margin-bottom: 20px !important;
        display: flex !important; /* 强制启用flex */
        flex-wrap: wrap !important; /* 强制换行 */
        gap: 10rpx !important; /* 强制间距 */
        padding: 0 !important; /* 清除默认内边距 */
        list-style: none !important; /* 清除列表样式（如果有） */

        ::v-deep .image-item {
          width: calc(50% - 5rpx) !important; /* 强制占50%宽度 */
          float: none !important; /* 禁用浮动（如果有） */
          margin: 0 0 10rpx 0 !important; /* 仅保留底部间距 */

          u-image {
            width: 100% !important;
            height: 300rpx !important;
            object-fit: cover !important;
            display: block !important; /* 确保图片为块级元素 */
          }
        }
      }
      .comment-section {
        width: 100%;
        padding: 10px 0;
        background-color: #f9f9f9;
        border-top: 1px solid #eee;
      }
    }
  }
  .fixed-input {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    padding: 10px;
    box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
    z-index: 10;
  }
}
</style>